import {create} from "zustand";
import {getFriendApplyListApi, rejectFriendApplyApi, acceptFriendApplyApi} from "@/services/api/friend-request";
import {FriendRequest, FriendRequestStatus} from "@/types/friend-request";
import {ResponseCode} from "@/types/api-common";

interface FriendRequestState {
    state: {
        friendApplyList: FriendRequest[]; // 好友申请列表
    };
    actions: {
        async: {
            getFriendApplyList: () => Promise<void>; // 获取好友申请列表
            acceptFriendApply: (requestId: string) => Promise<void>; // 接受好友申请
            rejectFriendApply: (requestId: string) => Promise<void>; // 拒绝好友申请
        }
    };
}

const FriendRequestStateStore = create<FriendRequestState>((set, get) => ({
    state: {
        friendApplyList: []
    },
    actions: {
        async: {
            // 获取好友申请列表
            getFriendApplyList: async () => {
                const res = await getFriendApplyListApi();
                if (res.data.code === ResponseCode.SUCCESS) {
                    set((state) => ({
                        state: {
                            ...state.state,
                            friendApplyList: res.data.data,
                        },
                    }));
                }
            },
            acceptFriendApply: async (requestId: string) => {
                const res = await acceptFriendApplyApi(requestId);
                if (res.data.code === ResponseCode.SUCCESS) {
                    set((state) => ({
                        state: {
                            ...state.state,
                            friendApplyList: state.state.friendApplyList.map((item) =>
                                item.id === requestId ? {...item, status: FriendRequestStatus.ACCEPTED} : item
                            ),
                        },
                    }));
                }
            },
            rejectFriendApply: async (requestId: string) => {
                const res = await rejectFriendApplyApi(requestId);
                if (res.data.code === ResponseCode.SUCCESS) {
                    set((state) => ({
                        state: {
                            ...state.state,
                            friendApplyList: state.state.friendApplyList.map((item) =>
                                item.id === requestId ? {...item, status: FriendRequestStatus.REJECTED} : item
                            ),
                        },
                    }));
                }
            },
        },
    },
}));

export default FriendRequestStateStore;